<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 *  News Model Class  
 *  
 * @package XGO CMS v2.0 
 * @subpackage News  
 * @author Manh Nguyen - 31/07/2012 
 * @link http://sunsoft.vn
 */
class News_model extends DataMapper {

    var $model = 'news_model';
    var $table = 'news';

    // --------------------------------------------------------------------
    // Construct
    // --------------------------------------------------------------------
    function __construct($id = NULL) {
//     	if($id!=NULL){
//     		print_r($id);
//     		exit;
//     	}

        parent::__construct($id);
//         $this->active = 1;
//         $this->feature = 1;
//         $this->hits = 0;
//        $this->partner_id = 'all';
        $this->validation = array(
            'feature' => array(
                'values' => array(
                    '0' => $this->lang->line('newspage'),
                    '1' => $this->lang->line('homepage')
                )
            ),
            'best_selling' => array(
                'values' => array(
                    '0' => $this->lang->line('no'),
                    '1' => $this->lang->line('yes')
                )
            ),
            'active' => array(
                'values' => array(
                    '0' => $this->lang->line('no'),
                    '1' => $this->lang->line('yes')
                )
            ),
            'new_item' => array(
                'values' => array(
                    '0' => $this->lang->line('no'),
                    '1' => $this->lang->line('yes')
                )
            )
        );
    }

    var $thumbnail = array(
        "noimg" => "data/images/.thumbs/noimg.jpg",
        "width" => "132",
        "height" => "100",
        "dir" => 'data/images/.thumbs/132x100/',
        "50x50" => array(
            "width" => "50",
            "height" => "50",
            "dir" => 'data/images/.thumbs/50x50/',
            "noimg" => "data/templates/frontend/gosu/images/icon_right.jpg",
        )
    );
    // --------------------------------------------------------------------
    // Relationships
    // --------------------------------------------------------------------

    var $has_many = array();
    // --------------------------------------------------------------------
    var $has_one = array(
        'creator' => array(
            'class' => 'user_model',
            'other_field' => 'created_news'
        ),
        'editor' => array(
            'class' => 'user_model',
            'other_field' => 'edited_news'
        ),
        'category' => array(
            'class' => 'category_model',
            'other_field' => 'news'
        )
    );
    // --------------------------------------------------------------------
    // Validation
    // --------------------------------------------------------------------	

    var $validation = array();

    /**
     * Default order in query select 
     */
    var $default_order_by = array('created' => 'desc');

    /**
     * string value of object
     * 
     * @access private
     * @param null
     * @return string 
     */
    function __toString() {
        return empty($this->title) ? '---empty---' : $this->title;
    }

    public function get_list($limit = 20, $partner_id = 'homepage') {
        $news = new News_model();
        $news->select('id, title, created, updated');
        $news->where('active', 1);
        $news->limit($limit);

        $news->group_start()
                ->where('partner_id', 'all')
                ->or_where('partner_id', $partner_id)
                ->group_end();

        $news->get();

        return $news;
    }

    /**
     * array feature of object
     *
     * @access public
     * @param bool
     * @return array
     */
    function feature_list($zero = FALSE) {
        $feature_list = $this->validation['feature']['values'];
        if ($zero) {
            $feature_list = array_merge(array('' => '--' . $this->lang->line('all') . '--'), $feature_list);
        }
        return $feature_list;
    }

    /**
     * string value of feature
     *
     * @access public
     * @return bool
     */
    function get_feature() {
        return $this->validation['feature']['values'][$this->feature];
    }

    /**
     * string value of active
     *
     * @access public
     * @param obj
     * @return bool
     */
    function get_active() {
        return $this->validation['active']['values'][$this->active];
    }

    public function get_search($keyword = NULL, $limit = '', $page = '') {
        $this->db
                ->select('news.id, news.title, news.code, news.description, news.image, news.content, news.created, news.category_id , news.new_price, news.old_price, category.code as category_code')
                ->from('news')
                ->join('category','category.id=news.category_id')
                
                ->where('news.active',1);
        
        $where="(`news`.`title` like '%$keyword%' or `news`.`description` like '%$keyword%' or `news`.`keyword` like '%$keyword%' or 1=2)";
        
//        foreach($category as $c)
//        {
//            $c=  mysql_escape_string($c);
//            $where.="`news`.`category_id` = '$c' or ";
//        }
//        $where.="1=2)";
        $this->db->where($where)
        
        ->order_by('news.created','desc');
        
        if($limit!='' && $page!='')
        {
            $start = $limit*($page-1);
            $this->db->limit($limit,$start);
        }
        
        return $this->db->get()->result();
    }
    
    public function get_advance_search($title = NULL,$fromdate = '', $todate = '', $category = 0)
    {
        $this->db
                ->select('news.title, news.code, news.description, news.content, news.created, news.category_id, category.code as category_code')
                ->from('news')
                ->join('category','category.id=news.category_id')
                ->like('news.title', $title)
                ->where('news.active',1)
                ->where('news.category_id',$category)
                ->where( "(`news`.`created` BETWEEN '$fromdate' AND '$todate')")
                //$this->db->where($where)
                ->order_by('news.created','desc');
                //->get();
        //echo $this->db->last_query();exit;
        return $this->db->get()->result();
    }
    
    public function count_by_search($title = NULL, $category = 0) {
        $this->select('title, code, description, content, created');
        $this->like('title', $title);
        $i = 0;
        foreach($category as $c)
        {
            if($i==0)
                $this->where('category_id',$c);
            else
                $this->or_where ('category_id', $c);
            $i++;
        }
        $this->where('active',1);
        $this->include_related('category', array('code', 'title'));
        $this->get();
        
        return $this->count();
    }    
    
    public function get_details($category_code = NULL, $code = NULL, $limit = 20, $offset = 0) {            
    	$this->select('id, title, hits, code, description, content, image, created, img_detail_1, img_detail_2, img_detail_3, sub_content, old_price, new_price, category_id');        
        $this->where('active', 1);
        $this->include_related('category', array('code', 'title'));
        $this->include_related('creator', array('firstname', 'lastname'));
        
        //$this->where('category_id', $category->id);
        if (isset($code)) {
            $this->where('code', $code);
            $this->get();
        }else{
        	$category = new Category_model();
        	$category->where('code', $category_code);
        	$category->select('id, code');
        	$category->get();
        	//$this->check_last_query();exit;
        	 
        	//get all children_id by category
        	$child_id = "";
        	$categorys = new Category_model();
        	$categorys->get_child_id($child_id, TRUE, $category->id);
        	$category->id = !is_null($child_id[0]) ? $child_id : 0;
        	$this->where_in('category_id', $child_id);
        	$this->order_by('id','DESC');
        	$this->get($limit, $offset);
        }

       //$this->check_last_query();exit;
        //update hits
        if ( isset($code) && $this->id>0 ) {
        	$this->update_hit();
        }
        
        return $this;
    }
    
    private function update_hit(){
    	$news = new News_model($this->id);
    	$news->hits++;
    	$news->save();
//     	$news->check_last_query();
//     	exit;
    }
    
    public function get_details_relate($category_code = NULL, $code = NULL, $limit = 30, $offset = 0, $not_code = '') {
        $category = new Category_model();
        $category->where('code', $category_code);
        $category->select('id, code');
        $category->order_by('id','ASC');
        $category->get();
        $this->select('id, title, code, description, content, created, image, category_id, img_detail_1, new_price, old_price');
        $this->where('category_id', $category->id);
        if (isset($not_code)) {
            $this->where_not_in('code', $not_code);
        }        
        if (isset($code)) {
            $this->where('code', $code);
        }
        $this->include_related('category', array('code', 'title'));
        $this->get($limit, $offset);
        //$this->check_last_query();exit;
        return $this;
    }    

    public function count_by_category($category_id = array()) {
        //$news = new News_model();
        
        $where = "(";
        foreach($category_id as $cid)
        {
            $where.="`news`.`category_id` =$cid or ";
        }
        $where.="1=2) and `news`.`active`=1";
        $this->strwhere($where);
        
        return $this->get()->result_count();
    }

    function get_by_category($category_id, $limit = 20, $page = 1) {
        $news = new News_model();
        $news->select('id, title, description, code, hits, link, url_target, created, content, image');	
        $news->where('category_id', $category_id);
        $news->where('active >', 0); 
        $news->include_related('category', array('code', 'title'));
        $news->order_by('created', 'desc');
        $news->get_paged_iterated($page, $limit);
        return $news;
    }    
    function get_by_parent_category($category_id, $limit = 20) {
        $category = new Category_model();
        $list = $category->get_list_category_child($category_id);

        $this->db->select('news.id, news.title, news.description, news.code, news.link, news.url_target, news.created, news.content, news.image, category.code as category_code');
        $this->db->from('news');
        $this->db->join('category','category.id=news.category_id');
        $this->db->where('news.active', 1);
        
        $where="(";
        
        foreach($list as $c)
        {
            $c=  mysql_real_escape_string($c->id);
            $where.="`news`.`category_id` = '$c' or ";
        }
        $where.="1=2)";
        $this->db->where($where);
         
        $this->db->order_by('news.created', 'desc');
        $this->db->limit($limit,0);
        return $this->db->get()->result();
    }
    function get_by_category_code($code, $limit = 20, $page = 1) {
        $start = $limit*($page-1);

        $this->db->select('news.id, news.title, news.code, news.image, news.category_id, news.description, news.new_price, news.old_price, category.code as category_code, category.title as category_title')
                ->from('news')
                ->join('category', 'category.id=news.category_id')
                ->where(array('category.code'=>$code,'news.active'=>1))
                ->order_by('news.created','desc')
                ->limit($limit,$start);//->get();print_r($this->db->last_query());exit;
        return $this->db->get()->result();
    }
   
    function get_all_by_category($category_id) {
        $news = new News_model();
        $news->select('id, title, description, code, link, url_target, created, content');
        $news->where('category_id', $category_id);
        $news->where('active >', 0);
        $news->include_related('category', array('code', 'title'));
        $news->get();
        return $news;
    }
    
    function get_last_news($catid, $limit=20) {
        if(!empty($catid)){
            $i = 0; 
            foreach($catid as $c){
                if($i == 0){
                        $this->where('category_id', $c);
                }else{
                        $this->or_where('category_id', $c);
                }
                $i++;
            }
            $this->include_related('category', array('title','code'));
            $this->include_related('creator', array('firstname', 'lastname'));
            $this->where('active', 1);
            $this->order_by('created', 'desc');
            if($limit){
                    $this->limit($limit);
            }
            return $this->get();
        }
        else{
                return 0;	
        }
    }
    
    function get_last_news_page($catid, $limit=20, $page)
    {
        
        if(!empty($catid)){
            $where = "(";
            foreach($catid as $c){
                $where.="`news`.`category_id` =$c or ";
            }
            $where.=" 1=2) and `news`.`active`=1";
            $this->strwhere($where);
            $this->include_related('category', array('title','code'));
            $this->order_by('created', 'desc');
            $this->get_paged_iterated($page,$limit);//echo $this->db->last_query();exit;
            return $this;
        }
        else{
                return 0;	
        }
    }
    
    function get_news($type, $limit = 20) {
        $news = new News_model();
        $news->select('id, title, code, link, url_target, created, content');
        $news->include_related('category', array('code','title'));
        $news->order_by('created', 'desc');
        $news->where('active', 1);
        $news->where('type', 'news');
        $news->get($limit);
        return $news;
    }    
	
    function get_new_by_category($id,$type = 'news',$limit = 5){
    	$news = new News_model();
    	$news->select('id, title, description, hits, code, link, url_target, created, content, image');
        $news->include_related('category', array('title','code'));
        $news->include_related('creator', array('firstname', 'lastname'));
        $news->order_by('created', 'desc');
        $news->where('active', 1);
        $news->where('type', $type);
        $news->where('category_id',$id);
        $news->get($limit);        
        return $news;
    }
    
    function get_new_by_option($option=array(), $limit=5)
    {
        $this->db->select('id, title, code, image, content, description, category_id, new_price, old_price, img_detail_1, img_detail_2, img_detail_3, new_image, best_selling_image')
                ->from('news')
                ->where('active',1);
        
        foreach($option as $key=>$value)
        {
            $this->db->where($key,$value);
        }
                
        $this->db->order_by('created','desc')
                ->limit($limit,0);
        return $this->db->get()->result();
    }
    
    function get_most_view($limit) {
        $news = new News_model();
        $news->select('id, title, code, link, url_target, created, content, hits');
        $news->include_related('category', 'code');
        $news->order_by('hits', 'desc');
        $news->limit($limit);
        $news->get();

        return $news;
    }

    function get_most_view_with_multi_category($category, $limit = 20, $offset = 0)
    {
        $this->db->select('news.title, news.code, news.hits, news.link, news.image, category.code as category_code');
        $this->db->from('news');
        $this->db->join('category','category.id=news.category_id');
        $this->db->where('news.active',1);
        
        $where = "(";
        foreach($category as $c)
        {
            $c=  mysql_escape_string($c);
            $where.="`news`.`category_id` = '$c' or ";
        }
        $where.="1=2)";
        
        $this->db->where($where);
        $this->db->order_by('news.hits','desc');
        $this->db->limit($limit,$offset);
        return $this->db->get()->result();
    }
    
    public function get_link_details() {
        return empty($this->link) ? site_url('news' . '/' . $this->category_code . '/' . $this->code . URL_SUFFIX) : $this->link;
    }

    /**
     * array active of object
     *
     * @access public
     * @param bool
     * @return array
     */
    function active_list($zero = FALSE) {
        $active_list = $this->validation['active']['values'];
        if ($zero) {
            $active_list = array_merge(array('' => '--' . $this->lang->line('all') . '--'), $active_list);
        }
        return $active_list;
    }

    function new_item_list($zero = FALSE) {
        $list = $this->validation['new_item']['values'];
        if ($zero) {
            $list = array_merge(array('' => '--' . $this->lang->line('all') . '--'), $list);
        }
        return $list;
    }
    
    function best_selling_list($zero = FALSE) {
        $list = $this->validation['best_selling']['values'];
        if ($zero) {
            $list = array_merge(array('' => '--' . $this->lang->line('all') . '--'), $list);
        }
        return $list;
    }
    
    /**
     * array category of object
     * 
     * @access public
     * @param bool
     * @return array
     */
    function category_list($zero = FALSE) {
        $category = new Category_model();
        $category->select('id, title');

        if ($zero) {
            $category_list = array('' => '--' . $this->lang->line('all') . '--');
        } else {
            $category_list = array();
        }

        foreach ($category->get() as $item) {
            $category_list[$item->id] = $item->title;
        }
        return $category_list;
    }

    function build_code($code) {
        if ($this->select('id')->where('code', $code)->get()->id) {
            $this->build_code($code . "-1");
        }else
            $this->code = $code; //fix return $code
    }

    function code_exists($code) {
        return $this->select('id')->where('code', $code)->get()->id;
    }

    function url_target_list() {
        return array(
            "normal" => $this->lang->line('normal'),
            "_blank" => $this->lang->line('_blank'),
            "_top" => $this->lang->line('_top'),
            "popup" => $this->lang->line('popup')
        );
    }

    public function img_first() {
    	$regex = '/src="((.+)\.(jpg|png|gif|jpeg|JPG|PNG|GIF|JPEG))"/';
    	//$regex = '/src="(https?:[\/.\w\s]+\.jpg|png|gif|jpeg|JPG|PNG|GIF|JPEG)"/';
    
    	preg_match($regex, $this->content, $n);
    	if (isset($n[1])) {
    		 
    		//v2.gosu.vn -> base_url();
    		return str_replace("http://v2.gosu.vn/", base_url(), urldecode($n[1]));
    		//return urldecode($n[1]);
    	}
    	//return "http://v2.gosu.vn/data/images/news/moto.jpg";
    }
    
    public function get_link_thumbnail($small = 0, $height = 145, $width = 100) {
    	//print_r($this->stored);
    	//echo $this->image;exit;
    	if ($this->image != "") {
    		$url = $this->image;
    	} else {
    		$url = $this->img_first();
    	}
    	//return $url;
    	//continue;
    	if ($small) {
    		$height = '50';
    		$width = '50';
    	}
    	//return $this->img_first();
    	if ($small == "-1") {//big
    		return $url;
    		continue;
    	}
    
    	$dir = $this->thumbnail['dir'] . $height . 'x' . $width . '/';
    
    	if (!is_dir($dir)) {
    		@mkdir($dir);
    	}
    
    	$thumbnail_url = $dir . md5($url . "47324723457345sdjfgsdf") . ".jpg";
    
    	if ($url) {
    		if (!file_exists($thumbnail_url)) {
    			if (file_exists(getcwd() . "/" . $url)) {//local
    				@$this->resize_crop(getcwd() . "/" . $url, $thumbnail_url, $width, $height);
    			} else {//remote
    				$headers = @get_headers($url);
    				if ($headers[0] == "HTTP/1.1 200 OK") {
    					@$this->resize_crop($url, getcwd() . "/" . $thumbnail_url, $width, $height);
    				}
    			}
    		}
    		//check thumbnail created
    		if (!file_exists($thumbnail_url)) {//create failed
    			return $this->thumbnail['noimg'];
    			continue;
    		} else {
    			return $thumbnail_url;
    			continue;
    		}
    	}
    	return $this->thumbnail['noimg'];
    
    	//data/templates/frontend/gosu/images/icon_right.jpg
    }
    
    private function resize_crop($src_image, $dest_image, $thumbnail_width, $thumbnail_height, $jpg_quality = 100) {
    
    
    	// Get dimensions of existing image
    	$image = getimagesize($src_image);
    
    	// Check for valid dimensions
    	if ($image[0] <= 0 || $image[1] <= 0) {
    		return false;
    	}
    
    	//image MIME-type
    	$image['format'] = strtolower(preg_replace('/^.*?\//', '', $image['mime']));
    
    	// Import image
    	switch ($image['format']) {
    		case 'jpg':
    		case 'jpeg':
    			$image_data = imagecreatefromjpeg($src_image);
    			break;
    		case 'png':
    			$image_data = imagecreatefrompng($src_image);
    			break;
    		case 'gif':
    			$image_data = imagecreatefromgif($src_image);
    			break;
    		default:
    			// Unsupported format
    			return false;
    			break;
    	}
    
    	$ratio_orig = $image[0] / $image[1];
    
    	if ($thumbnail_width / $thumbnail_height > $ratio_orig) {
    		$resize_height = $thumbnail_width / $ratio_orig;
    		$resize_width = $thumbnail_width;
    
    		//crop
    		$x_offset = 0;
    		$y_offset = $resize_height / 2 - ($thumbnail_height / 2);
    	} else {
    		$resize_width = $thumbnail_height * $ratio_orig;
    		$resize_height = $thumbnail_height;
    
    		//crop
    		$x_offset = $resize_width / 2 - ($thumbnail_width / 2);
    		$y_offset = 0;
    	}
    
    	//resize
    	$resize = imagecreatetruecolor(round($resize_width), round($resize_height));
    
    	if (imagecopyresampled($resize, $image_data, 0, 0, 0, 0, $resize_width, $resize_height, $image[0], $image[1])) {
    
    		//crop
    		$crop = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
    
    		if (imagecopyresampled($crop, $resize, 0, 0, $x_offset, $y_offset, $thumbnail_width, $thumbnail_height, $thumbnail_width, $thumbnail_height)) {
    
    			// Create thumbnail
    			switch (strtolower(preg_replace('/^.*\./', '', $dest_image))) {
    				case 'jpg':
    				case 'jpeg':
    					return imagejpeg($crop, $dest_image, $jpg_quality);
    					break;
    				case 'png':
    					return imagepng($crop, $dest_image);
    					break;
    				case 'gif':
    					return imagegif($crop, $dest_image);
    					break;
    				default:
    					// Unsupported format
    					return false;
    					break;
    			}
    
    			//purge tmp
    			imagedestroy($crop);
    			imagedestroy($resize);
    			imagedestroy($image_data);
    		} else {
    			return false;
    		}
    	}
    }

    
    function statistics_by_category(){
    	$category_important = 181;
    	
    	$this->select("COUNT(id) as count, category_id");
    	$this->group_by("category_id");
    	$this->get();
    	$return = $array = array();
    	foreach($this as $item){
    		if($item->count>0){
    			$array['category_id'][$item->category_id] 		= $item->category_id;
    			$array['count'][$item->category_id] 			= $item->count;
    		}    		
    	}
    	$category_obj = new Category_model();
    	$category_title = $category_obj->get_title_by_category_id_list($array['category_id']);
    	foreach($category_title as $item){
    		//if( array_key_exists($item->id, $array['count'])){    			
    			if($item->id ==$category_important){
    				$return['important'][$array['count'][$item->id]] 	= trim($item->title);
    			}else{
    				$return['normal'][$array['count'][$item->id]] 		= trim($item->title);
    			}
    		//}
    	}
    	return $return;
    	//$this->check_last_query();
    	//exit;
    }
   
    /**
     * array metadata for generate jquery grid.
     *
     * @access public
     * @param null
     * @return array
     */
    function jqgrid_metadata() {
        $category = new Category_model();
        $category_list = array(0 => '---' . $this->lang->line('cat') . " " . $this->lang->line('root') . '---');
        $category->get_list_title($category_list, TRUE, 2);

        //edittype: 'text', 'textarea', 'select', 'checkbox', 'password', 'button', 'image', 'file', 'custom'
        return array(
            'names' => array(
                'id',
                $this->lang->line('title'),
                $this->lang->line('cat'),
                $this->lang->line('creator'),
                $this->localize_label('editor'),
                $this->localize_label('created'),
                $this->lang->line('active'),
                //$this->lang->line('position'),
                $this->lang->line('viewed')
            ),
            'model' => array(
                array('name' => 'id',
                    'hidden' => TRUE,
                    'key' => TRUE,
                    'editrules' => array('edithidden' => TRUE)
                ),
                array('name' => 'title',
                    'searchoptions' => array(
                        'sopt' => array('cn', 'nc', 'eq', 'bw', 'bn', 'ew', 'en')
                    )
                ),
                array('name' => 'category',
                    'searchoptions' => array(
                        'sopt' => array('eq'),
                        'value' => $category_list//$this->category_list(TRUE)
                    ),
                    'stype' => 'select'
                ),
                array('name' => 'creator_id',
                    'searchoptions' => array(
                        'sopt' => array('cn', 'nc', 'eq', 'bw', 'bn', 'ew', 'en')
                    )
                ),
                array('name' => 'editor_id',
                    'searchoptions' => array(
                        'sopt' => array('cn', 'nc', 'eq', 'bw', 'bn', 'ew', 'en')
                    )
                ),
                array('name' => 'created',
                    'search' => FALSE
                ),
                array('name' => 'active',
                    'searchoptions' => array(
                        'sopt' => array('eq'),
                        'value' => $this->active_list(TRUE)
                    ),
                    'stype' => 'select'
                ),
//                array('name' => 'feature',
//                    'searchoptions' => array(
//                        'sopt' => array('eq'),
//                        'value' => $this->feature_list(TRUE)
//                    ),
//                    'stype' => 'select'
//                ),
                array('name' => 'hits',
                    'searchoptions' => array(
                        'sopt' => array('eq', 'gt', 'ge', 'lt', 'le')
                    )
                )
            )
        );
    }
}

/* End of file news_model.php */
/* Location: ./application/models/news_model.php */